<template>
  <v-card>
    <v-upload
      :beforeUpload="beforeUpload"
      :showUploadList="false"
      accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      action="/"
    >
      <v-button class="mb-5">
        <v-icon type="upload"></v-icon>导入Excel
      </v-button>
    </v-upload>

    <v-button @click="downTpl" class="mb-5 ml-10">下载模板</v-button>
    <vcu-table :loadOptions="options" height="300" ref="xTable"></vcu-table>

    <br />
    <br />
    <v-alert class="mb-10" type="info">
      <div slot="message">
        <div>importOptions 参数：</div>
        <div class="blue-text">
          <div>showTips : 是否显示默认判断条件提示窗，默认值为true</div>
          <div>
            condition : 自定义判断条件是否继续导入数据，默认值为null, 注意
            <span class="red-text">函数必须是异步的</span>
          </div>
        </div>
        <div class="red-text">注意: 如果某例全部都没有数据，此列不会出现在excelColumns</div>
      </div>
    </v-alert>

    <v-upload
      :beforeUpload="beforeUpload1"
      :showUploadList="false"
      accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      action="/"
    >
      <v-button class="mb-5">
        <v-icon type="upload"></v-icon>导入Excel
      </v-button>
    </v-upload>

    <vcu-table :importOptions="importOptions" :loadOptions="options" height="300" ref="xTable1"></vcu-table>
  </v-card>
</template>

<script>
import XEUtils from "xe-utils";
import XLSX from "xlsx";
import moment from "moment";
import { UtilTools } from "../../../../components/tools";
/*
 * 导入Excel
 */
const importExcel = async ({ file = null, vm = null, tableRef = "xTable", showTips = true, condition = null }) => {
  if (!file) {
    console.error("The file parameter cannot be empty");
    return false;
  }
  return new Promise(async (resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = async (ev) => {
      try {
        const data = ev.target.result;
        const workbook = XLSX.read(data, {
          type: "binary",
          cellDates: true,
        });
        const _sheets = workbook.Sheets[Object.keys(workbook.Sheets)[0]];
        const _sheetArray = XLSX.utils.sheet_to_json(_sheets);
        const _columns = vm.$refs[tableRef].getColumns();
        if (_columns.length == 0) {
          UtilTools.showTipsModal({
            content: "目标表格的表头数据不能为空",
          });
          resolve(false);
          return;
        }
        if (_sheetArray.length == 0) {
          UtilTools.showTipsModal({ content: "导入的EXLEC没有任务数据" });
          resolve(false);
          return;
        }
        let listTable = [],
          columnLists = [],
          columnTitles = [],
          excelTitles = [];
        XEUtils.arrayEach(_columns, (item) => {
          if (item.visible) {
            columnLists.push({
              property: item.property,
              title: item.title,
            });
            columnTitles.push(item.title);
          }
        });
        XEUtils.arrayEach(_sheetArray, (sheet) => {
          XEUtils.objectEach(sheet, (item, key) => {
            if (!XEUtils.includes(excelTitles, key)) excelTitles.push(key);
          });
        });
        console.info(1111);
        const columnDefect = XEUtils.filter(columnTitles, (item) => !XEUtils.includes(excelTitles, item));
        const excelDefect = XEUtils.filter(excelTitles, (item) => !XEUtils.includes(columnTitles, item));

        if (columnDefect.length && showTips) {
          const modalRes = await UtilTools.showConfirmModal({
            content: `<p>目标表格比导入的数据多了${columnDefect.length}列：${columnDefect.join(" , ")};</p><p>是否继续导入数据</p> `,
          });
          if (!modalRes) {
            resolve(false);
            return;
          }
        }

        if (excelDefect.length && showTips) {
          const modalRes = await UtilTools.showConfirmModal({
            content: `<p>导入的数据比目标表格多了${excelDefect.length}列：${excelDefect.join(" , ")};</p><p>是否继续导入数据</p> `,
          });
          if (!modalRes) {
            resolve(false);
            return;
          }
        }

        if (XEUtils.isFunction(condition)) {
          const modalRes = await condition({
            tableColumns: _columns,
            excelColumns: excelTitles,
          });
          if (!modalRes) {
            resolve(false);
            return;
          }
        }

        XEUtils.arrayEach(_sheetArray, (sheet) => {
          let rowTable = {};
          XEUtils.objectEach(sheet, (item, key) => {
            const currItem = XEUtils.filter(columnLists, (i) => i.title == key);
            if (currItem.length) {
              rowTable[currItem[0].property] = moment.isDate(item) ? UtilTools.getmoment(item) : item;
            }
          });
          listTable.push(rowTable);
        });
        vm.$refs[tableRef].setDatas(listTable);
        resolve(listTable);
      } catch (e) {
        vm.$error({
          title: "提示",
          content: "文件类型不正确！",
        });
      }
    };
    fileReader.readAsBinaryString(file);
  });
};
export default {
  props: {},
  computed: {},
  data() {
    return {
      options: {
        headUrl: "api/header/excelImport",
      },
      importOptions: {
        showTips: false,
        condition: async ({ tableColumns, excelColumns }) => {
          return new Promise(async (resolve, reject) => {
            this.$confirm({
              title: "提示",
              content: "导入的数据有问题是否继续导入？",
              onOk() {
                resolve(true);
              },
              onCancel() {
                resolve(false);
              },
            });
          });
        },
      },
    };
  },
  methods: {
    downTpl() {
      window.open(`http://10.16.241.70:8034/files/宁德康复导入.xls`, "myIframe");
    },
    beforeUpload(file) {
      importExcel({ file, vm: this, tableRef: "xTable" });
      return false;
    },
    beforeUpload1(file) {
      importExcel({ file, vm: this, tableRef: "xTable1", ...this.importOptions });
      return false;
    },
  },
  created() {},
  beforeDestroy() {},
};
</script>
<style lang="less" scoped>
</style>